package com.weic.easycache.framework;

public class Result<D> {
	public static final int STATUS_WAITING				= 0;
	public static final int STATUS_LOADING				= 1;
	/**变化的是progress和message之一或者都变化，progress值取决于当前任务index占队列count的百分比，
	 * message取决于Biz.getMessage()返回值和任务失败时候的返回值。**/
	public static final int STATUS_PROGRESS				= 2;
	public static final int STATUS_COMPLETE				= 3;
	public static final int STATUS_FAILURE				= 4;
	public static final int STATUS_UPDATE				= 5;

	public volatile int status;
	public volatile int taskid;
	/**取值范围 0~100，小数长度为0~2位**/
	public volatile float progress;
	/**显示给用户的消息，包含进度的信息和错误的信息。可配置，具体配置方式参见 {@link com.weic.easycache.helper.wei.c.framework.MsgHelper MsgHelper}.**/
	public volatile String message;
	public volatile D data;

	Result() {}

	Result(int status, D data) {
		this.status = status;
		this.data = data;
	}

	@SuppressWarnings("unchecked")
	public static <T> Result<T> obtain() {
		synchronized (sPoolSync) {
			if (sPool != null) {
				Result<T> m = (Result<T>)sPool;
				sPool = m.next;
				m.next = null;
				sPoolSize--;
				return m;
			}
		}
		return new Result<T>();
	}

	public void recycle() {
		clearForRecycle();

		synchronized (sPoolSync) {
			if (sPoolSize < MAX_POOL_SIZE) {
				next = sPool;
				sPool = this;
				sPoolSize++;
			}
		}
	}

	private void clearForRecycle() {
		status = 0;
		taskid = 0;
		progress = 0;
		message = null;
		data = null;
	}

	private Result<?> next;
	private static final Object sPoolSync = new Object();
	private static Result<?> sPool;
	private static int sPoolSize = 0;

	private static final int MAX_POOL_SIZE = 50;
}